<template>
  <CustomModal
    title="设备管理"
    v-model="visible"
    isTabbar
    :showCancelButton="false"
    :showConfirmButton="false"
  >
    <view class="modal-content">
      <view v-if="updateStatus === '1'" class="container">
        <image
          :src="getViteImageUrl('recipe/loading.png')"
          mode="aspectFit"
          class="icon update-icon"
        />
        <view class="content-text">正在下载更新本地设备数据库......</view>
      </view>
      <view v-if="updateStatus === '2'" class="container">
        <image
          :src="getViteImageUrl('recipe/downloaded.png')"
          mode="aspectFit"
          class="icon"
        />
        <view class="content-text">已下载更新本地设备数据库！</view>
      </view>
    </view>
    <up-toast ref="uToastRef" />
  </CustomModal>
</template>

<script setup>
defineOptions({
  name: 'UpdateDevice',
  inheritAttrs: false
})

const visible = defineModel({
  type: Boolean,
  default: false
})
const emit = defineEmits(['confirm'])

// 数据缓存
const { userInfo } = storeToRefs(useUserStore())
const { allDeviceList, bindDeviceList } = storeToRefs(useDeviceStore())
const updateStatus = ref('1') // 1-下载中 2-下载完成 3-下载失败
const uToastRef = ref(null)

onMounted(_ => {
  getDataList()
})

function getDataList() {
  const appId = g_utils.getAppId()
  g_api.device
    .apiDownloadDeviceInfo({
      tenantId: userInfo.value.tenantId,
      appId
    })
    .then(({ code, data }) => {
      if (code === 200 && data) {
        allDeviceList.value = data
        // 从云端同步已绑定的设备
        const dataList = g_.cloneDeep(data).filter(item => {
          item.appId = appId
          return item.type === 1 && item.bind === 1
        })
        const deviceList = bindDeviceList.value.reduce((prev, curr) => {
          if (curr.status * 1 === g_i.device.DeviceStatus.Idle) {
            // 对于空闲设备，检查云端是否有匹配项，只取有更新的设备信息
            const matchedItem = dataList.find(
              dataItem => dataItem.sn === curr.sn && dataItem.updateTime > curr.updateTime
            )
            matchedItem
              ? prev.push(g_i.apiDataFormat(matchedItem, g_i.device.deviceInfo))
              : ''
          } else {
            // 保留非空闲状态的设备
            prev.push(curr)
          }
          return prev
        }, [])
        const sns = new Set(deviceList.map(item => item.sn))
        // 筛选出云端中未在本地设备列表中出现的新设备
        const filterData = dataList.filter(item => {
          if (!sns.has(item.sn)) {
            Object.assign(item, g_i.apiDataFormat(item, g_i.device.deviceInfo))
            return true
          }
        })
        bindDeviceList.value = [...deviceList, ...filterData]
        console.log('清洗后的设备列表：', bindDeviceList.value)
        updateStatus.value = '2'
      } else {
        updateStatus.value = '1'
        visible.value = false
      }
    })
    .catch(err => {
      updateStatus.value = '1'
      visible.value = false
    })
    .finally(_ => {})
}
</script>

<style lang="scss" scoped>
.modal-content {
  display: flex;
  flex-direction: column;
  margin: 82rpx 0 42rpx;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 0 26rpx;
  .icon {
    width: 86rpx;
    height: 86rpx;
    margin: 0 auto;
    &.update-icon {
      animation: spin 2s linear infinite;
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .content-text {
    margin: 52rpx 0 0;
    line-height: 26rpx;
    text-align: center;
    font-size: 26rpx;
    font-weight: 400;
    color: var(--color-333);
  }
}
</style>
